package com.zmzncs.lmtc.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zmzncs.lmtc.common.pojo.*;
import com.zmzncs.lmtc.common.pojo.daoer.*;
import com.zmzncs.lmtc.module.park.pojo.park_info_daoer.ParkInfoDaoer;
import com.zmzncs.lmtc.module.park.service.ParkInfoDaoerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 道尔
 */
@Slf4j
@Component
public class DaoerApiUtil {

    //测试环境
//    final static String REFERER = "https://cloud-beta.drzk.cn";

    //PRO环境
    final static String REFERER = "https://cloud-2018.drzk.cn";

    final static String SUCCESS_STATUS = "1";
    final static String TOKEN_URL = "/api/index/auth/token";
    final static String GET_CAR_FEE = "/api/index/tempFee/getcarfee";
    final static String ONANDOFF =  "/api/index/onandoff";
    final static String GET_CHANNELS =  "/api/index/getchannels";
//    final static String GET_CARFEE =  "/apiDocumentation?url=tempCar&name=0";
    final static String GET_CARFEE =  "/api/index/tempFee/getcarfee";
    final static String GET_PARKING =  "/api/getparking";
    final static String GATE_ON_OFF =  "/api/index/onandoff";
    final static String GET_MONTH_AMOUNT =  "/api/index/monthlycar/long-rental-rate";
    final static String CREATE_MONTH =  "/api/index/monthlycar/create";
    final static String MONTH_RENEWAL =  "/api/index/monthlycar/newdate";
    final static String MONTH_DELETE =  "/api/index/monthlycar/del";
    final static String USER_MONTH_INFO =  "/api/index/monthlycar/info";

    @Autowired
    ParkInfoDaoerService parkInfoDaoerService;

    private static DaoerApiUtil daoerApiUtil;
    @PostConstruct
    public void init() {
        daoerApiUtil = this;
    }

    /**
     * 获取token
     */
    public static synchronized  String getToken(String parkId) {
        MapCacheManager.deleteTimeOut();
        String token = (String)MapCacheManager.getCache("token");
        if(StringUtils.isBlank(token)){
            ParkInfoDaoer parkInfoDaoer = daoerApiUtil.parkInfoDaoerService.getInfoByParkId(parkId);
            if (parkInfoDaoer == null || StringUtils.isBlank(parkInfoDaoer.getAppName())){
                log.error("获取道尔AppName空");
            }

            Map<String, Object> paramsa = Maps.newHashMap();
            paramsa.put("appName", parkInfoDaoer.getAppName());
            paramsa.put("parkId", parkId );//停车场ID
            String jsonParams =  JSON.toJSONString(paramsa);
            String response =  HttpUtil.getIntance().postJson(REFERER+TOKEN_URL, jsonParams);
            String status = JSONObject.parseObject(response).get("status").toString();
            if(SUCCESS_STATUS.equals(status)){
                token = JSONObject.parseObject(response).get("data").toString();
                MapCacheManager.setCache("token",token,7200*1000);
                return token;
            }
            log.error("获取道尔token错误：" + response);
        }
        return token;
    }

    /**
     * 获取车场通道
     * @param parkId
     * @return
     */
    public static ChnnelsBody getChannels(String parkId) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CHANNELS, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        String status = resultHead.getHead().getStatus();
        if(SUCCESS_STATUS.equals(status)){
            ChnnelsBody chnnels = JsonUtil.JSONToObj(resultStr, ChnnelsBody.class);
            return chnnels;
        }
        return null;
    }

    /**
     * 道闸开关操作
     * @param parkId 第三方应用车场编号
     * @param channelId 通道ID
     * @param channelIdStatus 1开启 2 关闭
     * @return
     */
    public static GateOnOff gateOnOff(String parkId, String channelId, Integer channelIdStatus) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("channelId", channelId);//通道ID
        params.put("channelIdStatus", channelIdStatus);//1开启 2 关闭

        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GATE_ON_OFF, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        String status = resultHead.getHead().getStatus();
        if(SUCCESS_STATUS.equals(status)){
            GateOnOff gateOnOff = JsonUtil.JSONToObj(resultStr, GateOnOff.class);
            return gateOnOff;
        }
        return null;
    }

    /**
     * 获取临时车缴纳金额
     * @param parkId    第三方应用车场编号
     * @param carNo 车牌号码
     */
    public static CarFeeRes getcarfee(String parkId, String carNo) {
        log.info("获取临时车缴纳金额：【{}】【{}】", parkId, carNo);

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CARFEE, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        try {
            ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
            String status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                CarFeeRes carFeeRes = JsonUtil.JSONToObj(resultStr, CarFeeRes.class);
                return carFeeRes;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return null;
    }

    /**
     * 获取停车场信息
     * @param parkId    第三方应用车场编号
     */
    public static ParkingInfo getParking(String parkId) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        String resultStr = HttpUtil.getIntance().get(REFERER+GET_PARKING+"/"+parkId,
                null, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        String status = resultHead.getHead().getStatus();
        if(SUCCESS_STATUS.equals(status)){
            ParkingInfo parkingInfo = JsonUtil.JSONToObj(resultStr, ParkingInfo.class);
            return parkingInfo;
        }
        return null;
    }

    /**
     * 获取月租费率
     * @param parkId    第三方应用车场编号
     */
    public static MonthAmount getMonthAmount(String parkId) {
        log.info("获取停车场信息：【{}】", parkId);
        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        String resultStr = HttpUtil.getIntance().get(REFERER+GET_MONTH_AMOUNT+"/"+parkId,
                null, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        String status = resultHead.getHead().getStatus();

        if(SUCCESS_STATUS.equals(status)){
            MonthAmount monthAmount = JsonUtil.JSONToObj(resultStr, MonthAmount.class);
            return monthAmount;
        }
        return null;
    }

    /**
     * 购买月卡  开户
     * @param createMonth
     * @return
     */
    public static Map<String,String> creatMonth(CreateMonth createMonth) {
        Map<String,String> map = new HashMap<>();

        if (createMonth == null){
            map.put("status","0");
            map.put("message","购买月卡失败，月租信息为null");
            return map;
        }
        String token = getToken(createMonth.getParkId());
        if(StringUtils.isBlank(token)){
            map.put("status","0");
            map.put("message","Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", createMonth.getParkId());//停车场ID
        params.put("carNo", createMonth.getCarNo());//车牌号码
        params.put("cardTypeId", createMonth.getCardTypeId());//卡类型编号：11~18:月租车A~H,41~42:免费车A~B,51~58:储值车A~H
        params.put("startTime", createMonth.getStartTime());//月租开始时间 yyyy-MM-dd HH:mm:ss
        params.put("endTime", createMonth.getEndTime());//月租结束时间 yyyy-MM-dd HH:mm:ss
        params.put("balanceMoney", createMonth.getBalanceMoney());//收费金额
        params.put("payType", createMonth.getPayType());//0 现金 1微信 2支付宝
        params.put("contactName", createMonth.getContactName());//人员名称
        params.put("concatPhone", createMonth.getConcatPhone());//人员手机号码

        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+CREATE_MONTH, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        String status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status",status);
        map.put("message",message);
        return map;
    }


    /**
     * 月租车基本信息
     * @param parkId    第三方应用车场编号
     * @param carNo 车牌号码
     */
    public static UserMonthInfo getUserMonthInfo(String parkId,String carNo) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        String jsonParams =  JSON.toJSONString(params);

        String resultStr = HttpUtil.getIntance().postJson(REFERER+USER_MONTH_INFO, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        try {
            ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
            String status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                UserMonthInfo monthInfo = JsonUtil.JSONToObj(resultStr, UserMonthInfo.class);
                return monthInfo;
            }
            String message = resultHead.getHead().getMessage();
            log.info(message);

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 月卡续期
     * @param monthRenewal
     * @return
     */
    public static Map<String,String> monthRenewal(MonthRenewal monthRenewal) {
        Map<String,String> map = new HashMap<>();

        if (monthRenewal == null){
            map.put("status","0");
            map.put("message","月卡续期，月租信息为null");
            return map;
        }
        String token = getToken(monthRenewal.getParkId());
        if(StringUtils.isBlank(token)){
            map.put("status","0");
            map.put("message","Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", monthRenewal.getParkId());//停车场ID
        params.put("carNo", monthRenewal.getCarNo());//车牌号码
        params.put("newStartTime", monthRenewal.getNewStartTime());//月租开始时间 yyyy-MM-dd HH:mm:ss
        params.put("newEndTime", monthRenewal.getNewEndTime());//月租结束时间 yyyy-MM-dd HH:mm:ss
        params.put("balanceMoney", monthRenewal.getBalanceMoney());//收费金额
        params.put("payType", monthRenewal.getPayType());//0 现金 1微信 2支付宝

        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+MONTH_RENEWAL, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        String status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status",status);
        map.put("message",message);
        return map;
    }

    /**
     * 月卡销户
     * @param parkId 第三方应用车场编号
     * @param carNo 车牌号码
     * @return
     */
    public static String monthDelete(String parkId,String carNo) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return "Token为空";
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码

        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+MONTH_DELETE, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        String message = resultHead.getHead().getMessage();
        return message;
    }

}
